//
//  SearchViewController.m
//  厚积薄发
//
//  Created by 侯振兴 on 14/12/31.
//  Copyright (c) 2014年 侯振兴. All rights reserved.
//

#import "SearchViewController.h"
#import "ConnectUrl.h"
#import "ReadingRoomModel.h"
#import "ConnectModel.h"
#import "DetailsViewController.h"
#import "HistoryBace.h"
#import "HistoryModel.h"
#import "SearchView.h"
#import "LibraryViewController.h"//进入编辑
#define kBlueColor [UIColor colorWithRed:129/255.0 green: 198/255.0 blue: 221/255.0 alpha: 1.0]

@interface SearchViewController ()

@end

@implementation SearchViewController

- (void)dealloc
{
    [_dics release];
    [_table release];
    [_model release];
    [_path release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        NSArray *array1 = [NSArray arrayWithObjects:JingPin, @"-2", nil];
        NSArray *array2 = [NSArray arrayWithObjects:Hide, @"-1", nil];
        NSArray *array3 = [NSArray arrayWithObjects:Social, @"6", nil];
        NSArray *array4 = [NSArray arrayWithObjects:Political, @"9", nil];
        NSArray *array5 = [NSArray arrayWithObjects:History, @"7", nil];
        NSArray *array6 = [NSArray arrayWithObjects:Culture, @"8", nil];
        NSArray *array7 = [NSArray arrayWithObjects:Economics, @"10", nil];
        NSArray *array8 = [NSArray arrayWithObjects:Science, @"12", nil];
        NSArray *array9 = [NSArray arrayWithObjects:Healthy, @"16", nil];
        NSArray *array10 = [NSArray arrayWithObjects:Life, @"1", nil];
        NSArray *array11 = [NSArray arrayWithObjects:Beauty, @"2", nil];
        NSArray *array12 = [NSArray arrayWithObjects:Food, @"17", nil];
        NSArray *array13 = [NSArray arrayWithObjects:Furniturn, @"4", nil];
        NSArray *array14 = [NSArray arrayWithObjects:Parenting, @"5", nil];
        NSArray *array15 = [NSArray arrayWithObjects:Constellation, @"3", nil];
        NSArray *array16 = [NSArray arrayWithObjects:Leisure, @"27", nil];
        NSArray *array17 = [NSArray arrayWithObjects:Emotional, @"14", nil];
        NSArray *array18 = [NSArray arrayWithObjects:Mind, @"13", nil];
        NSArray *array19 = [NSArray arrayWithObjects:Humor, @"18", nil];
        NSArray *array20 = [NSArray arrayWithObjects:Note, @"15", nil];
        NSArray *array21 = [NSArray arrayWithObjects:Eduction, @"26", nil];
        NSArray *array22 = [NSArray arrayWithObjects:Workplace, @"24", nil];
        NSArray *array23 = [NSArray arrayWithObjects:Computer, @"25", nil];
        NSArray *array24 = [NSArray arrayWithObjects:Car, @"23", nil];
        NSArray *array25 = [NSArray arrayWithObjects:Tourism, @"11", nil];
        NSArray *array26 = [NSArray arrayWithObjects:Photography, @"22", nil];
        NSArray *array27 = [NSArray arrayWithObjects:Art, @"21", nil];
        NSArray *array28 = [NSArray arrayWithObjects:Beautiful, @"20", nil];
        NSArray *array29 = [NSArray arrayWithObjects:Original, @"28", nil];
        self.dics = [NSMutableArray arrayWithObjects:array1,array2,array3,array4,array5,array6,array7,array8,array9,array10,array11,array12,array13,array14,array15,array16,array17,array18,array19,array20,array21,array22,array23,array24,array25,array26,array27,array28,array29, nil];
        
        self.model = [[ReadingRoomModel alloc] init];
        _model.os = @"ios";
        _model.ver = @"2.2.0.0";
        _model.op = @"gac";
        _model.p = @"1";
        _model.w = @"280";
        _model.cFrom = @"";
        _model.cid = [[_dics firstObject] lastObject];
        [_model release];
        self.tableArray = [NSMutableArray array];
//        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//        [button setFrame:CGRectMake(20, 25, 40, 30)];
//        [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
//        [button setTitle:@"返回" forState:UIControlStateNormal];
//        [button setTitle:@"返回" forState:UIControlStateHighlighted];
//
//        [button addTarget:self action:@selector(createButtonPopBackLibrary) forControlEvents:UIControlEventTouchUpInside];
//        [self.view addSubview:button];

    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = kBlueColor;
    self.navigationItem.title = @"搜索";
    self.navigationController.navigationBar.barTintColor = kBlueColor;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchHistory:) name:@"SEARCH" object:nil];
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.hidden = NO;
    self.path = JingPin;
    [self createSearch];
    [self createView];
    [self createHeader];
    [self createTable];

}

#pragma mark -
#pragma mark 3.改动search坐标
#warning createSearch

- (void)createButtonPopBackLibrary
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)createSearch
{
    SearchView *search = [[SearchView alloc] initWithFrame:CGRectMake(20, 20, self.view.frame.size.width - 40, self.view.frame.size.height - 169)];
    //y120->164
    [self.view addSubview:search];
    [search release];
}

- (void)searchHistory: (NSNotification *)noti
{
    NSString *history_tit = [noti.userInfo objectForKey:@"tit"];
    UITextField *filed = (UITextField *)[self.view viewWithTag:10];
    filed.text = history_tit;
    [self buttonAction];
    
}
#pragma mark -
#pragma mark 改动坐标
#warning createHeader

- (void)createHeader
{
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@"精品",@"转藏",@"社会",@"政治",@"历史",@"文化",@"财经",@"科学",@"健康",@"生活",@"美容",@"美食",@"家具",@"育儿",@"星座",@"休闲",@"情感",@"心灵",@"幽默",@"美文",@"教育",@"职场",@"电脑",@"爱车",@"旅游",@"摄影",@"艺术",@"美图",@"原创", nil];
    UIScrollView * scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(20, 20, self.view.frame.size.width - 40, 30)];//坐标x20->60 y40->84
    scroll.tag = 1000;
    scroll.layer.cornerRadius = 10;
    scroll.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:scroll];
    [scroll release];
    scroll.contentSize = CGSizeMake(29 * 70, 30);
    scroll.bounces = NO;
    for (int i = 0; i < 29; i++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(70 * i, 0, 60, 30)];
        button.tag = 10000 + i;
        button.layer.cornerRadius = 10;
        NSString *str = [array objectAtIndex:i];
        [button setTitle:str forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(goTo:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:button];
        [button release];
    }
    UIButton *button = (UIButton *)[scroll viewWithTag:10000];
    NSInteger red = arc4random()%256;
    NSInteger blue = arc4random()%256;
    NSInteger green = arc4random()%256;
    UIColor *color = [[UIColor alloc] initWithRed:red/256.0f green:green/256.0f blue:blue/256.0f alpha:1];
    button.backgroundColor = color;
    [color release];
    [button setTitleColor:[UIColor whiteColor] forState: UIControlStateNormal];
}

- (void)goTo: (UIButton *)button
{
    UIScrollView *scroll = (UIScrollView *)[self.view viewWithTag:1000];
    for (int i = 0; i < 29; i++)
    {
        UIButton *allButton = (UIButton *)[scroll viewWithTag:10000 + i];
        [allButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        allButton.backgroundColor = [UIColor whiteColor];
    }
    NSInteger red = arc4random()%256;
    NSInteger blue = arc4random()%256;
    NSInteger green = arc4random()%256;
    UIColor *color = [[UIColor alloc] initWithRed:red/256.0f green:green/256.0f blue:blue/256.0f alpha:1];
    button.backgroundColor = color;
    [color release];
    [button setTitleColor:[UIColor whiteColor] forState: UIControlStateNormal];
    _path = [self urlStr:button.tag];
    _model.cid = [[_dics objectAtIndex:button.tag - 10000] lastObject];
}

- (NSString *)urlStr: (NSInteger)tag
{
    switch (tag - 10000) {
        case 0:
            return JingPin;
            break;
        case 1:
            return Hide;
            break;
        case 2:
            return Social;
            break;
        case 3:
            return Political;
            break;
        case 4:
            return History;
            break;
        case 5:
            return Culture;
            break;
        case 6:
            return Economics;
            break;
        case 7:
            return Science;
            break;
        case 8:
            return Healthy;
            break;
        case 9:
            return Life;
            break;
        case 10:
            return Beauty;
            break;
        case 11:
            return Food;
            break;
        case 12:
            return Furniturn;
            break;
        case 13:
            return Parenting;
            break;
        case 14:
            return Constellation;
            break;
        case 15:
            return Leisure;
            break;
        case 16:
            return Emotional;
            break;
        case 17:
            return Mind;
            break;
        case 18:
            return Humor;
            break;
        case 19:
            return Note;
            break;
        case 20:
            return Eduction;
            break;
        case 21:
            return Workplace;
            break;
        case 22:
            return Computer;
            break;
        case 23:
            return Car;
            break;
        case 24:
            return Tourism;
            break;
        case 25:
            return Photography;
            break;
        case 26:
            return Art;
            break;
        case 27:
            return Beautiful;
            break;
        case 28:
            return Original;
            break;
        default:
            break;
    }
    return @"";
    
}
#pragma mark -
#pragma mark 2.改动坐标 field button
#warning createView
- (void)createView
{
    UITextField *field = [[[UITextField alloc] initWithFrame:CGRectMake(19, 70, self.view.frame.size.width - 120, 30)] autorelease];//y80->120
    field.tag = 10;
    field.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:field];
    [self.view setBackgroundColor:kBlueColor];
    UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(self.view.frame.size.width - 100, 70, 80, 30);//y->122
    button.backgroundColor = [UIColor clearColor];
    [button setTitle:@"搜索" forState:UIControlStateNormal];
    button.layer.cornerRadius = 0;
    [button setBackgroundColor:kBlueColor];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:20]];
    [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];



}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITextField * field = (UITextField *)[self.view viewWithTag:10];
    [field resignFirstResponder];
}

#warning 解析
- (void)buttonAction
{
    [_tableArray removeAllObjects];
    _table.frame = CGRectMake(20, 120, self.view.frame.size.width - 40, self.view.frame.size.height - 132);
    _table.layer.cornerRadius = 2;
    UITextField *filed = (UITextField *)[self.view viewWithTag:10];
    [filed resignFirstResponder];
    
#warning history 添加
    HistoryModel *model = [HistoryModel historyWithHistory_tit:filed.text];
    [HistoryBace insertIntoHistoryWithHistoryModel:model];
    NSString *path = [_path stringByReplacingOccurrencesOfString:@"dn=20" withString:@"dn=200"];
    [ConnectModel connectModelWithUrlStr:path parmaters:nil block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if ([_path isEqualToString:JingPin]) {
            NSArray * arrays = [dic objectForKey:@"NAItem"];
            for (NSDictionary *dics in arrays) {
                NSString *string = [dics objectForKey:@"Tit"];
                NSRange range = [string rangeOfString:filed.text];
                if (range.length != 0) {
                    [_tableArray addObject:dics];
                }
            }
            
            [_table reloadData];
        }if ([_path isEqualToString:Hide]) {
            NSArray * arrays = [dic objectForKey:@"RSListItem"];
            for (NSDictionary *dics in arrays) {
                NSString *string = [dics objectForKey:@"Tit"];
                NSRange range = [string rangeOfString:filed.text];
                if (range.length != 0) {
                    [_tableArray addObject:dics];
                }
            }
            [_table reloadData];
        }else{
            NSArray * arrays = [dic objectForKey:@"RCItem"];
            for (NSDictionary *dics in arrays) {
                NSString *string = [dics objectForKey:@"Tit"];
                NSRange range = [string rangeOfString:filed.text];
                if (range.length != 0) {
                    [_tableArray addObject:dics];
                }
            }
            [_table reloadData];
        }
    }];
}
#warning createTable
- (void)createTable
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(-self.view.frame.size.width, 114, self.view.frame.size.width - 40, self.view.frame.size.height - 169) style:UITableViewStylePlain];
    _table.delegate = self;
    _table.dataSource = self;
    _table.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_table];
    [_table release];
    [_table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_tableArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    NSDictionary *dic =[_tableArray objectAtIndex:indexPath.row];
    [cell.textLabel setText:[dic objectForKey:@"Tit"]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic =[_tableArray objectAtIndex:indexPath.row];
    _model.aid = [dic objectForKey:@"Aid"];
    
    DetailsViewController *detail = [[DetailsViewController alloc] init];
    detail.parameter = _model;
    [self presentViewController:detail animated:NO completion:nil];
    [detail release];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
